# @FileName  : main.py
# @Time      : 2022/3/5 17:18
# @Author    : LuZhaoHui
# @Software  : PyCharm
import os
import time

from conf import *
from msql import *
from mainwindow import Ui_MainWindow
from login import Ui_FormLogin
from passwd import Ui_DialogPass
# from dirlist import Ui_UiDirList
from getDir import Ui_UiDirList

from tcp import *
from webClient import *

VER = '1.5.9.2'

CHECKDATA = [0, '', 0, 0, 0, '', '']


class imagePass(QDialog, Ui_DialogPass):
    def __init__(self, opPass):
        super(imagePass, self).__init__()
        self.setupUi(self)
        self.oldPass = opPass
        self.newPass = ''
        self.exit = False
        self.init()

    def init(self):
        self.pushButtonOk.clicked.connect(self.save)

    def save(self):
        if self.lineEditOldPass.text().strip() != self.oldPass:
            showBox(self, "原密码错误，请重新输入")
            self.lineEditOldPass.clear()
            return
        if self.lineEditNewPass.text().strip() != self.lineEditRePass.text().strip():
            showBox(self, "2次密码不相等，请重新输入")
            self.lineEditRePass.clear()
            return
        self.exit = True
        self.newPass = self.lineEditNewPass.text().strip()
        self.close()

    def closeEvent(self, event):
        if self.exit:
            pass


class getDirUI(QDialog, Ui_UiDirList):
    getDirExit = pyqtSignal(str)

    def __init__(self, namelist):
        super(getDirUI, self).__init__()
        self.setupUi(self)
        self.dirs = namelist
        self.init()

    def init(self):
        self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint)
        self.setWindowTitle('选择分配目录，双击确认')
        self.setList()

    def setList(self, namelist=None):
        # 获取分配目录
        if namelist != None:
            self.dirs = namelist
        self.exit = False
        self.curDir = ''
        self.listWidgetDir.clear()
        for dir in self.dirs:
            self.listWidgetDir.addItem(QListWidgetItem('%-12s ' % (dir[1])))
        self.listWidgetDir.doubleClicked.connect(self.selectDirOk)

    # 双击本地打印列表显示
    def selectDirOk(self):
        pos = self.listWidgetDir.currentRow()
        self.curDir = self.dirs[pos][1]
        if showBoxYes(self, "请确认领取目录[%s]" % (self.curDir)):
            self.exit = True
            # self.getDirExit.emit(self.curDir)
            # self.hide()
            self.close()

    # def closeEvent(self, event):
    #     event.accept()
    #     if self.exit:
    #         self.getDirExit.emit(self.curDir)
    #     else:
    #         self.getDirExit.emit('')


class imageLogin(QWidget, Ui_FormLogin):
    def __init__(self, main, conf):
        super(imageLogin, self).__init__()
        self.setupUi(self)
        self.main = main
        self.conf = conf
        self.op = self.conf.varConf['CurOp']
        self.opName = ''
        self.opRole = 0
        self.opRoleStr = ''
        self.title = self.conf.varConf['Title']
        self.mac = get_mac_address()
        self.exit = False
        self.init()

    def init(self):
        saveLog('start')
        # self.setWindowTitle(self.photoConfig.DesignVar['Title'])
        self.setWindowTitle('登录窗口')
        self.setWindowIcon(QIcon(LOGO))
        self.main.loginState = False
        w = 448
        h = 260
        self.resize(w, h)
        self.setFixedSize(w, h)
        img = QImage()
        img.load(TITLELOGO)
        self.labelLogo.setPixmap(QPixmap.fromImage(img.scaled(w, h, Qt.KeepAspectRatio)))
        self.pushButtonLogin.clicked.connect(self.loginExit)
        # self.pushButtonSetPass.clicked.connect(self.loginSet)
        self.lineEditOp.clear()
        self.lineEditOp.setValidator(QIntValidator(self.lineEditOp))
        self.lineEditOp.setFocus()
        if self.op:
            self.lineEditOp.setText('%d' % (self.op))
            self.lineEditPass.setFocus()

    def loginExit(self):
        # 操作员认证
        try:
            self.op = int(self.lineEditOp.text())
        except ValueError:
            self.op = 0
        err = 920
        if self.op and len(self.lineEditPass.text().strip()):
            result = self.main.dataMysql.loginOp(self.op, self.lineEditPass.text().strip(), self.mac)
            # 判断登录结果
            if result != None and len(result) >= 1 and result[0][0] == self.op:
                # 登录
                self.opName = result[0][1]
                self.opRole = result[0][2]
                self.opRoleStr = result[0][3]
                # 正常使用
                self.exit = True
                self.close()
                return
            else:
                if result != None:
                    err = result[0][0]
        else:
            if self.op <= 0:
                err = 920
            else:
                err = 921
        showBox(self, self.main.dataMysql.errStr(abs(err)))
        print(err)
        if abs(err) == 920:
            self.lineEditOp.setFocus()
        elif abs(err) == 921:
            self.lineEditPass.clear()
            self.lineEditPass.setFocus()

    def selectOpChange(self, index):
        if index < 0:
            return
        self.op = self.codeList[index]

    def closeEvent(self, event):
        if self.exit:
            saveLog('login main %d' % (self.op))
            event.accept()
            self.main.setOp(self.op, self.opName, self.opRole, self.opRoleStr)
            self.main.show()
        else:
            if showBoxYes(self, "登录将退出，是否确认?  "):
                saveLog('exit')
                self.main.loginState = False
                self.main.exit()
                self.main.close()
                event.accept()
            else:
                event.ignore()

    # 键盘事件
    def keyPressEvent(self, event):
        key = event.key()
        if key in (Qt.Key_Return, Qt.Key_Enter):
            self.loginExit()


class ExLabel(QLabel):
    labelSig = pyqtSignal(int)

    def __int__(self, parent=None):
        super(ExLabel, self).__init__(parent)
        # self.main = main
        self.pos = -1

    def setPos(self, pos):
        self.pos = pos

    def mousePressEvent(self, e):
        self.labelSig.emit(self.pos)

    # def connectSlot(self, func):
    #     self.labelSig.connect(func)

    # def leaveEvent(self, e):
    #     print('leaveEvent')
    #
    # def enterEvent(self, e):
    #     print('enterEvent')


class ExListWidget(QListWidget):
    listSig = pyqtSignal(int)

    def __int__(self, parent=None):
        super(ExListWidget, self).__init__(parent)
        print('create ExListWidget')

    # 键盘事件
    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Up:
            self.listSig.emit(-1)
            print('Key_Up')
        elif event.key() == Qt.Key_Down:
            self.listSig.emit(1)
            print('Key_Down')
        else:
            super(ExListWidget, self).keyPressEvent(event)


class imageCheckScpRun(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(imageCheckScpRun, self).__init__(parent)
        self.setupUi(self)
        self.initRedirection()
        self.config = imageCheckScpConf('conf.ini')
        self.initVar()
        self.init()

    def initRedirection(self):
        self.stdoutbak = sys.stdout
        self.stderrbak = sys.stderr

    def resetRedirection(self):
        sys.stdout = self.stdoutbak
        sys.stderr = self.stderrbak

    def closeEvent(self, event):
        if showBoxYes(self, "系统将退出，是否确认?  "):
            self.exit()
            event.accept()
        else:
            event.ignore()

    def keyPressEvent(self, event):
        pass

    def exit(self):
        # if self.dirUI != None:
        #     self.dirUI.close()
        self.dataMysql.addActLog(302, '')
        self.resetRedirection()
        self.dataMysql.exit()
        self.upSsh.sshClose()

    def initVar(self):
        # 操作员
        self.op = 0
        self.opName = ''
        self.opRole = 0
        self.opRoleStr = ''
        # 当前目录
        self.curPath = self.config.varConf['CurPath']
        self.checkPath = CHECKDATA
        # 文件列表
        self.curFileList = []
        self.isShowImage = False
        # 目录列表
        self.mainPath = self.config.varConf['MainPath']
        if not os.path.exists(self.mainPath):
            os.makedirs(self.mainPat)
        self.cachePath = self.config.varConf['CachePath']
        if not os.path.exists(self.cachePath):
            os.makedirs(self.cachePath)
        self.curDirList = []
        # SCP 服务器
        self.isSsh = self.config.varScp['IsScp']
        self.upSsh = sshClient(self.config.varLog['LogPath'])
        self.upSsh.setConf(self.config.varScp['ScpHost'],
                           self.config.varScp['ScpPort'],
                           self.config.varScp['ScpUser'],
                           self.config.varScp['ScpPass'],
                           self.config.varScp['ScpPath'])
        # MYSQL 服务器
        self.isMysql = self.config.varMsql['IsDb']
        self.dataMysql = mysqlProc(self.config.varMsql['DbHost'],
                                   self.config.varMsql['DbPort'],
                                   self.config.varMsql['DbUser'],
                                   self.config.varMsql['DbPass'],
                                   self.config.varMsql['DbName']
                                   )
        # 目录选择UI
        # self.dirUI = None
        self.checkImageThread = None
        self.scpImageThread = None

    def init(self):
        if self.config.varConf['WindowMax'] > 0:
            self.showMaximized()
        # self.setWindowFlags(Qt.WindowCloseButtonHint | Qt.WindowMinimizeButtonHint)
        self.setWindowIcon(QIcon(LOGO))
        self.setWindowTitle('%s Ver[%s]' % (self.config.varConf['Title'], VER))

    # 状态栏显示信息
    def showStatusMsg(self, pos, msg):
        self.statusLabel[pos].setText(msg)

    # 刷新显示时间
    def showCurrentTime(self):
        # 获取系统当前时间
        time = QDateTime.currentDateTime()
        # 设置系统时间的显示格式
        timeDisplay = time.toString(' yyyy-MM-dd hh:mm:ss dddd  ')
        # 状态栏显示
        self.showStatusMsg(7, timeDisplay)

    # 状态栏-刷新时间
    def statusShowTime(self):
        self.timer = QTimer()
        self.timer.timeout.connect(self.showCurrentTime)
        self.timer.start(1000)

    # 数据库-刷新时间
    def mysqlShowTime(self):
        self.timerMysql = QTimer()
        self.timerMysql.timeout.connect(self.showMysqlStatus)
        self.timerMysql.start(2000)

    # 显示MYSQL
    def showMysqlStatus(self):
        # 状态栏显示
        msqlStatus = 'mysql %s' % ('Ok' if self.dataMysql.status else 'Err')
        self.showStatusMsg(6, msqlStatus)

    def statusShowMessage(self):
        self.statusLabel = []
        self.statusLabelLength = (150, 180, 200, 200, 200, 180, 180, 220)
        for i in range(len(self.statusLabelLength)):
            # label = QLabel()
            label = ExLabel()
            label.setAlignment(Qt.AlignCenter)
            label.setFixedWidth(self.statusLabelLength[i])
            self.statusLabel.append(label)
            self.statusBar.addPermanentWidget(self.statusLabel[i], stretch=i)
        # 按钮添加到状态栏
        self.setPassButton = QPushButton("设置密码")
        self.statusBar.insertPermanentWidget(5, self.setPassButton)
        self.setPassButton.clicked.connect(self.setPassword)

    def initUI(self):
        self.statusShowMessage()
        self.statusShowTime()
        self.mysqlShowTime()
        setComboBoxHeight(self.comboBoxImageDir, 16)
        self.comboBoxImageDir.currentIndexChanged.connect(self.curImageDir)
        # 刷新文件
        self.pushButtonFlushImageFile.clicked.connect(self.flushImageFile)
        self.pushButtonRenImageFile.clicked.connect(self.renImageFile)
        # 列表控件
        self.exList = ExListWidget()
        self.groupBoxFile.layout().addWidget(self.exList)
        self.listWidgetImageFileList.hide()
        self.initImageDir()
        self.exList.listSig.connect(self.selectPos)
        self.exList.itemClicked.connect(self.selectFile)
        # self.listWidgetImageFileList.itemClicked.connect(self.selectFile)
        self.pushButtonImageLeftRotate.clicked.connect(self.leftRotateImage)
        self.pushButtonImageRightRotate.clicked.connect(self.rightRotateImage)
        # 领取目录
        self.pushButtonGetImageFile.clicked.connect(self.getImageDir)
        # 条件，开始核查
        for k, v in self.dataMysql.conditionDict.items():
            s = 'self.checkBoxCheckCondition%d.setText(\'%s\')' % (k, v)
            eval(s)
        self.pushButtonFileCheck.clicked.connect(self.checkFile)
        self.selectPos(0)
        # SCP测试
        self.lineEditScpPath.setText('%s:%d@%s->%s' %
                                     (self.upSsh.ip,
                                      self.upSsh.port,
                                      self.upSsh.user,
                                      self.upSsh.workPath))
        self.pushButtonScpTest.clicked.connect(self.scpTest)
        # 上传图片
        self.pushButtonScpFile.clicked.connect(self.scpImage)
        # self.pushButtonScpFileCheck.clicked.connect(self.scpImageCheck)
        self.flushUI()

    def flushUI(self):
        self.labelFileInfo.setText('%d' % (len(self.curFileList)))
        self.pushButtonFlushImageFile.setEnabled(self.checkPath[0])
        self.pushButtonRenImageFile.setEnabled(self.checkPath[0]
                                               and self.checkPath[5]
                                               and len(self.curFileList))
        self.pushButtonFileCheck.setEnabled(self.checkPath[0]
                                            and self.checkPath[5]
                                            and len(self.curFileList))
        self.pushButtonScpFile.setEnabled(self.checkPath[0]
                                          and self.checkPath[5]
                                          and len(self.curFileList)
                                          and (self.checkPath[6] == 1))

    def halt(self):
        self.exit()
        sys.exit(1)

    def setOp(self, op, name, role, roleStr):
        # 登录操作员
        self.op = op
        self.opName = name
        self.opRole = role
        self.opRoleStr = roleStr
        self.dataMysql.setSys(self.op, VER)
        self.dataMysql.addActLog(301, '%d[%s]' % (self.opRole, self.opRoleStr))
        self.config.writeVarConf('CONF', 'CurOp', op)
        self.initUI()
        self.showStatusMsg(5, '%d-%s-%s' % (self.op, self.opName, self.opRoleStr))

    def initImageDir(self):
        # 初始图片目录
        print('initImageDir')
        self.exList.clear()
        # self.listWidgetImageFileList.clear()
        self.curFileList.clear()
        self.comboBoxImageDir.clear()
        self.comboBoxImageDir.blockSignals(True)
        self.curDirList.clear()
        index = -1
        for d in os.listdir(self.mainPath):
            name = pathJoin(self.mainPath, d)
            print(d)
            if os.path.isdir(name):
                self.comboBoxImageDir.addItem(d)
                if d == self.curPath and index < 0:
                    index = len(self.curDirList)
                self.curDirList.append(name)
        self.comboBoxImageDir.blockSignals(False)
        if index < 0 and len(self.curDirList):
            index = 0
        if self.comboBoxImageDir.currentIndex() == index:
            self.curImageDir(index)
        else:
            self.comboBoxImageDir.setCurrentIndex(index)

    def curImageDir(self, index):
        # 选择当前目录
        if index < 0:
            return
        path = self.comboBoxImageDir.currentText()
        # 验证目录
        self.checkPath = self.checkCurDir(path)
        self.curPath = path
        self.flushUI()
        if self.checkPath[0] == 0:
            # 未分配目录
            showBox(self, "目录错误，请重新选择或领取目录")
            self.config.varConf['CurPath'] = ''
            return
        else:
            if self.config.varConf['CurPath'] != path:
                self.config.varConf['CurPath'] = path
                self.config.writeVarConf('CONF', 'CurPath', self.config.varConf['CurPath'])
        self.lineEditDirState.setText('%s-%s' %
                                      (self.dataMysql.lockStr(self.checkPath[5]),
                                       self.dataMysql.checkStr(self.checkPath[6])))
        self.lineEditDirClass.setText(self.dataMysql.classStr(self.checkPath[1]))
        self.dateEditDirYear.setDate(QDate(self.checkPath[2], 1, 1))
        self.spinBoxDirNo.setValue(self.checkPath[3])
        self.spinBoxFileNums.setValue(self.checkPath[4])
        self.labelFileOtherInfo.setText(self.checkPath[7])
        self.flushImageFile()

    def checkCurDir(self, dir):
        # 验证当前目录
        ret = self.dataMysql.getDir(dir)
        if ret == None:
            return CHECKDATA
        dirList = list(ret[0][:7])
        dirList.append('%s-%s-%d-%s-%s-%d' % (ret[0][7],
                                              ret[0][8],
                                              ret[0][9],
                                              ret[0][10],
                                              ret[0][11],
                                              ret[0][12]))
        return dirList

    def addCurDir(self, dirName):
        # 当前选择目录
        print('addCurDir')
        self.curPath = dirName
        self.config.varConf['CurPath'] = dirName
        self.config.writeVarConf('CONF', 'CurPath', self.config.varConf['CurPath'])

    def setCurDir(self, dir):
        # 分配目录
        print('setCurDir')
        ret = self.dataMysql.setDir(dir)[0]
        if ret[0] == 0:
            return True
        else:
            showBox(self, self.dataMysql.errStr(abs(ret[0])))
            return False

    # def choiceImageDir(self):
    #     # 选择目录
    #     curPath = self.config.varFile['CurPath']
    #     path = QFileDialog.getExistingDirectory(self, " 选择图片目录 ", curPath)
    #     if os.path.exists(path):
    #         if path != curPath:
    #             self.config.varFile['CurPath'] = path
    #             self.config.writeVarConf('FILE', 'CurPath', path)
    #             self.initImageDir()
    def selectPos(self, pos):
        if pos == 0:
            index = pos
        else:
            index = self.exList.selectedIndexes()[0].row()
            print('selectPos %d %d' % (pos, index))
            index = pos + index
        if index < 0 or index >= self.exList.count():
            return
        self.exList.setCurrentRow(index)
        self.exList.itemClicked.emit(self.exList.item(index))

    def selectFile(self):
        # 选择当前文件
        self.isShowImage = False
        if len(self.curFileList):
            index = self.exList.selectedIndexes()[0].row()
            # index = self.listWidgetImageFileList.selectedIndexes()[0].row()
            if index >= 0:
                name = self.curFileList[index]
                info = getImgFile(name)
                mean = getImgMean(name)
                if info[1] == 0 or info[2] == 0:
                    self.labelImageInfo.setText(name)
                    self.labelImage.setPixmap(QPixmap(''))
                    self.labelImage.setText('非有效图片文件')
                else:
                    self.isShowImage = True
                    self.labelImageInfo.setText('%s %dx%d %d,%d %s %.2f' %
                                                (name,
                                                 info[1], info[2],
                                                 info[3], info[4],
                                                 getColor(info[5]),
                                                 round(mean, 2)))
                    showLabelImage(self.labelImage, name, True)
        self.pushButtonImageLeftRotate.setEnabled(self.isShowImage)
        self.pushButtonImageRightRotate.setEnabled(self.isShowImage)

    def leftRotateImage(self):
        if len(self.exList.selectedIndexes()) == 0:
            return
        index = self.exList.selectedIndexes()[0].row()
        # if len(self.listWidgetImageFileList.selectedIndexes()) == 0:
        #     return
        # index = self.listWidgetImageFileList.selectedIndexes()[0].row()
        name = self.curFileList[index]
        imageRotate(name, Image.Transpose.ROTATE_90)
        showLabelImage(self.labelImage, name, True)

    def rightRotateImage(self):
        if len(self.exList.selectedIndexes()) == 0:
            return
        index = self.exList.selectedIndexes()[0].row()
        # if len(self.listWidgetImageFileList.selectedIndexes()) == 0:
        #     return
        # index = self.listWidgetImageFileList.selectedIndexes()[0].row()
        name = self.curFileList[index]
        imageRotate(name, Image.Transpose.ROTATE_270)
        showLabelImage(self.labelImage, name, True)

    def flushImageFile(self):
        # 清屏
        self.labelImage.setPixmap(QPixmap(''))
        self.labelImageInfo.setText('')
        self.textEditCheckResult.clear()
        self.exList.clear()
        # self.listWidgetImageFileList.clear()
        # 刷新文件
        self.exList.blockSignals(True)
        # self.listWidgetImageFileList.blockSignals(True)
        self.curFileList.clear()
        dirPath = pathJoin(self.mainPath, self.curPath)
        for f in os.listdir(dirPath):
            name = pathJoin(dirPath, f)
            print(name)
            if os.path.isfile(name):
                self.curFileList.append(name)
                self.exList.addItem(
                    QListWidgetItem('%4d  %-12s  %s' %
                                    (self.exList.count() + 1,
                                     f, getFileInfo(name))))
                # self.listWidgetImageFileList.addItem(
                #     QListWidgetItem('%4d  %-12s  %s' %
                #                     (self.listWidgetImageFileList.count() + 1,
                #                      f, getFileInfo(name))))
        self.exList.blockSignals(False)
        # self.listWidgetImageFileList.blockSignals(False)
        self.labelFileInfo.setText('%d' % (len(self.curFileList)))
        self.flushUI()
        self.selectPos(0)
        ret = self.dataMysql.modDir(self.curPath, len(self.curFileList))
        if ret[0] == 0:
            self.dataMysql.addActLog(314, '刷新目录 [%s] ret=%d' % (dirPath, ret[0]))

    def renImageFile(self):
        # 更名
        dirNameList = self.curPath.split('-')
        renameList = []
        for i, name in enumerate(self.curFileList):
            bpath = os.path.dirname(name)
            bname = os.path.basename(name)
            ext = os.path.splitext(bname)[1]
            xhName = '%06d%s' % (int(i / 2) + 1, 'B' if (i % 2) else 'A')
            newFile = bpath + '/' + dirNameList[len(dirNameList) - 1] + '-' + xhName + ext
            renameList.append((name, newFile))
        for ff in renameList[::-1]:
            os.rename(ff[0], ff[1])
        self.flushImageFile()

    def getImageDirName(self, name):
        print('getImageDirName')
        if len(name):
            # 选择分配目录
            dirPath = pathJoin(self.mainPath, name)
            print(dirPath)
            if not os.path.exists(dirPath):
                print('mkdir')
                os.mkdir(dirPath)
            if self.setCurDir(name):
                self.addCurDir(name)
                self.initImageDir()

    def getImageDir(self):
        # 领取目录
        print('getImageDir')
        getLists = self.dataMysql.getDirs()
        if getLists == None:
            showBox(self, "无可分配目录，请联系管理员")
            return
        dirUI = getDirUI(getLists)
        dirUI.exec()
        if dirUI.exit:
            self.getImageDirName(dirUI.curDir)

    def setPassword(self):
        # 设置密码
        setUI = imagePass(self.opPass)
        setUI.exec()
        # if setUI.exit:
        #     self.main.dataMysql.setOpPass(self.opPass)

    # def setDirNest(self, checked):
    #     # 设置目录嵌套
    #     if self.config.varFile['DirNest'] != int(checked):
    #         self.config.varFile['DirNest'] = int(checked)
    #         self.config.writeVarConf('FILE', 'DirNest', int(checked))

    # def setSaveLog(self, checked):
    #     # 设置日志
    #     if self.config.varLog['IsLog'] != int(checked):
    #         self.config.varLog['IsLog'] = int(checked)
    #         self.config.writeVarConf('LOG', 'IsLog', int(checked))

    def showCheckFile(self, flist):
        # 线程显示结果
        if len(flist) == 1:
            self.labelCheckInfo.setText('check %d' % (flist[0]))
        elif len(flist) == 3:
            self.textEditCheckResult.append('[%s] %s' % (flist[1], flist[2]))
        elif len(flist) == 4:
            # [0, errNums, checkResultStr, conditionStr])
            if flist[1] == 0:
                checkState = 1
                checkResultStr = '文件数[%d],核查通过' % (len(self.curFileList))
            else:
                checkState = 9
                checkResultStr = '文件数[%d],错误数[%d],结果:%s' % (len(self.curFileList),
                                                                    flist[1],
                                                                    flist[2])
            ret = self.dataMysql.checkDir(self.curPath, flist[3], checkResultStr, checkState)
            if ret[0] == 0:
                self.checkPath = self.checkCurDir(self.curPath)
                self.lineEditDirState.setText('%s-%s' %
                                              (self.dataMysql.lockStr(self.checkPath[5]),
                                               self.dataMysql.checkStr(self.checkPath[6])))
                self.flushUI()

    def checkFile(self):
        # 开始核查
        self.textEditCheckResult.clear()
        keys = []
        checkConditionStr = ''
        for k, v in self.dataMysql.conditionDict.items():
            s = 'self.checkBoxCheckCondition%d.isChecked()' % (k)
            if not eval(s):
                continue
            keys.append(k)
            checkConditionStr = checkConditionStr + '%d:%s,' % (k, v)
        checkConditionStr = checkConditionStr.rstrip(',')
        # 核查线程
        self.checkImageThread = CheckFileThread(self.config,
                                                keys, checkConditionStr,
                                                self.curPath,
                                                self.curFileList)
        self.checkImageThread.update_item.connect(self.showCheckFile)
        self.checkImageThread.start()

    def scpTest(self):
        # 测试SCP
        ret = self.upSsh.getDirList()
        if ret == None:
            self.labelScpStatusInfo.setText('服务器连接断开')
        else:
            self.labelScpStatusInfo.setText('服务器连接正常 目录数[%d]' % (len(ret)))

    def showScpFile(self, flist):
        # 线程显示结果
        if len(flist) == 1:
            self.labelScpInfo.setText('scp %d  nums %d,%d' % (flist[0], self.scpNums[0], self.scpNums[1]))
        elif len(flist) == 7:
            # i + 1, byte, info, name, bname, scpName, md5
            if flist[1] == flist[2][0]:
                self.scpNums[0] += 1
                self.textEditCheckResult.append('[%s] 成功' % (flist[4]))
                # MYSQL
                ret = self.dataMysql.addFile(self.curPath,
                                             flist[4],
                                             pathJoin(self.upSsh.workPath, flist[5]),
                                             flist[0],
                                             getFileAB(flist[4]),
                                             flist[2][1], flist[2][2],
                                             getColorCode(flist[2][5]),
                                             flist[6],
                                             flist[2][0]
                                             )
                print(ret)
            else:
                self.scpNums[1] += 1
                self.textEditCheckResult.append('[%s] 失败' % (flist[4]))
                saveLog('put file [%s->%s] 失败' % (flist[3], flist[5]), log='error')
        else:
            self.labelScpInfo.setText('scp nums %d,%d' % (self.scpNums[0], self.scpNums[1]))
            print('scp end')

    def scpImage(self):
        # 上传图片
        self.scpNums = [0, 0]
        self.textEditCheckResult.clear()
        self.scpImageThread = ScpFileThread(self.upSsh, self.curPath, self.curFileList)
        self.scpImageThread.update_item.connect(self.showScpFile)
        self.scpImageThread.start()

    def scpImageCheck(self):
        # 校验图片
        self.textEditCheckResult.clear()
        self.scpImageThread = ScpFileThread(self.upSsh, self.curPath, self.curFileList)
        self.scpImageThread.update_item.connect(self.showScpFile)
        self.scpImageThread.start()


class CheckFileThread(QThread):
    # 核查线程
    update_item = pyqtSignal(list)

    def __init__(self, config, conditionKeys, conditionStr, curPath, filList):
        super().__init__()
        self.conf = config
        self.keys = conditionKeys
        self.keyStr = conditionStr
        self.path = curPath
        self.list = filList

    def run(self):
        saveLog('%s begin' % (self.__class__.__name__))
        dirNameList = self.path.split('-')
        errNums = 0
        checkResultStr = ''
        for i, name in enumerate(self.list):
            self.update_item.emit([i + 1])
            # 判断条件
            info = getImgFile(name)
            mean = getImgMean(name)
            bname = os.path.basename(name)
            pname = os.path.splitext(bname)[0]
            pnameList = pname.split('-')
            ext = os.path.splitext(bname)[1][-3:]
            isRead = False
            isMean = True
            if info[1] > 0 and info[2] > 0:
                # 是否黑图
                isRead = True
                checkMean = self.conf.varCheck['CheckMean']
                if checkMean > 0.0 and mean <= checkMean:
                    isMean = False
            errMsg = ''
            for k in self.keys:
                if k == 1:
                    # 文件可读
                    if not isRead:
                        errMsg = errMsg + '非有效图片文,'
                    if not isMean:
                        errMsg = errMsg + '图片可能黑图,'
                elif k == 2:
                    # DPI = 300
                    if not isRead:
                        continue
                    if (info[3] != self.conf.varCheck['CheckImageDpi']
                            or info[4] != self.conf.varCheck['CheckImageDpi']):
                        errMsg = errMsg + 'DPI非%s,' % (self.conf.varCheck['CheckImageDpi'])
                elif k == 3:
                    # 是否JPG
                    if ext.lower() != self.conf.varCheck['CheckImageExt'].lower():
                        errMsg = errMsg + '非JPG文件,'
                elif k == 6:
                    # 是否彩色
                    if not isColor(info[5]):
                        errMsg = errMsg + '非彩色图片,'
                elif k == 4:
                    # 文件序号是否连续
                    if len(pnameList) != 2:
                        errMsg = errMsg + '文件命名错误,'
                    else:
                        ab = pnameList[1][-1:].upper()
                        if ab not in 'AB':
                            errMsg = errMsg + '文件命名非AB,'
                        else:
                            xh = 0
                            try:
                                xh = int(pnameList[1][:-1])
                            except Exception:
                                xh = 0
                            xh = xh * 2 - 1
                            if ab == 'B':
                                xh = xh + 1
                            if xh != (i + 1):
                                errMsg = errMsg + '文件序号错误,'
                    # 文件名和目录匹配
                    if len(pnameList) != 2 or pnameList[0] != dirNameList[len(dirNameList) - 1]:
                        errMsg = errMsg + '文件名和目录匹配,'
            if len(errMsg):
                errMsg = errMsg.rstrip(',')
                errNums = errNums + 1
                checkResultStr = checkResultStr + '%s;' % (errMsg)
                self.update_item.emit([i + 1, bname, errMsg])
        # 核查完毕
        self.update_item.emit([0, errNums, checkResultStr, self.keyStr])


class ScpFileThread(QThread):
    # 上传线程
    update_item = pyqtSignal(list)

    def __init__(self, upSsh, curPath, filList):
        super().__init__()
        self.ssh = upSsh
        self.path = curPath
        self.list = filList

    def run(self):
        saveLog('%s begin' % (self.__class__.__name__))
        for i, name in enumerate(self.list):
            self.update_item.emit([i + 1])
            info = getImgFile(name)
            bname = os.path.basename(name)
            scpName = pathJoin(self.path, bname)
            # 上传
            md5 = GetFileMd5(name)
            byte = self.ssh.putFile(name, scpName)
            self.update_item.emit([int(i / 2) + 1, byte, info, name, bname, scpName, md5])
        self.update_item.emit([])


class ScpFileThread(QThread):
    # 上传线程
    update_item = pyqtSignal(list)

    def __init__(self, upSsh, curPath, filList):
        super().__init__()
        self.ssh = upSsh
        self.path = curPath
        self.list = filList

    def run(self):
        saveLog('%s begin' % (self.__class__.__name__))
        for i, name in enumerate(self.list):
            self.update_item.emit([i + 1])
            info = getImgFile(name)
            bname = os.path.basename(name)
            scpName = pathJoin(self.path, bname)
            # 上传
            md5 = GetFileMd5(name)
            while True:
                byte = self.ssh.putFile(name, scpName)
                if byte > 0:
                    break
                self.msleep(1000)
            self.update_item.emit([int(i / 2) + 1, byte, info, name, bname, scpName, md5])
        self.update_item.emit([])


class ScpFileCheckThread(QThread):
    # 校验线程
    update_item = pyqtSignal(list)

    def __init__(self, upSsh, curPath, filList):
        super().__init__()
        self.ssh = upSsh
        self.path = curPath
        self.list = filList

    def run(self):
        saveLog('%s begin' % (self.__class__.__name__))
        for i, name in enumerate(self.list):
            self.update_item.emit([i + 1])
            info = getImgFile(name)
            bname = os.path.basename(name)
            scpName = pathJoin(self.path, bname)
            # 上传
            md5 = GetFileMd5(name)
            byte = self.ssh.putFile(name, scpName)
            self.update_item.emit([int(i / 2) + 1, byte, info, name, bname, scpName, md5])
        self.update_item.emit([])


if __name__ == '__main__':
    app = QApplication(sys.argv)

    main = imageCheckScpRun()
    # main.show()
    # 登录
    login = imageLogin(main, main.config)
    login.show()

    sys.exit(app.exec_())
